﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Skyhook.AI.PathFinder
{
    class PointDataCache
    {
        PointData[] Elements = null;
        int ElementsCount = 0;
        PointData FirstEmptyElement = null;

        public PointDataCache(int size)
        {
            Elements = new PointData[size];
            for (int i = 0; i < size; i++)
            {
                Elements[i] = new PointData(0, 0, 0);
            }
        }

        public PointData GetPointData(int x, int y, int f)
        {
            if (FirstEmptyElement != null)
            {
                PointData result = FirstEmptyElement;
                FirstEmptyElement = result.Values.NextCache;
                result.Values.X = x;
                result.Values.Y = y;
                result.F = f;
                result.NextMinF = null;
                result.PreviousMinF = null;
                result.Values.Previous = null;
                result.Values.NextCache = null;
                result.PreviousSorter = null;
                result.NextSorter = null;
                return result;
            }
            if (ElementsCount < Elements.Length)
            {
                PointData result = Elements[ElementsCount];
                result.Values.X = x;
                result.Values.Y = y;
                result.F = f;
                result.NextMinF = null;
                result.PreviousMinF = null;
                result.Values.Previous = null;
                result.Values.NextCache = null;
                result.PreviousSorter = null;
                result.NextSorter = null;
                ElementsCount++;
                return result;
            }
            throw new Exception("PointDataCache overflow!");
        }

        public void RemovePointData(PointData data)
        {
            data.NextMinF = null;
            data.PreviousMinF = null;
            data.Values.Previous = null;
            data.Values.NextCache = FirstEmptyElement;
            FirstEmptyElement = data;
        }

        public void Clear()
        {
            FirstEmptyElement = null;
            ElementsCount = 0;
        }
    }
}
